<?php

declare(strict_types=1);

namespace App\Http\Controllers\Manage;

use App\Http\Services\Manage\ImportDataService;
use App\Repositories\Manage\LouAddressRepository;
use Exception;
use Maatwebsite\Excel\Facades\Excel;

class LouAddressController extends ManageBaseController
{

    private $addressRepo = null;

    public function __construct(LouAddressRepository $addressRepo)
    {
        parent::__construct();
        $this->addressRepo = $addressRepo;
    }

    public function index()
    {
        $filter['pid'] = intval(request()->get("pid", 0));
        $filter['keywords'] = request()->get("keywords", "");
        $res = $this->addressRepo->getList($filter, $this->pageNum, 100);
        return retSuc($res);
    }

    public function update($id = null)
    {
        $data = request()->all();
        $last_id = $this->addressRepo->saveOrUpdate($data, $id ?? 0);
        if (!$last_id) {
            return retFail("更新失败");
        }

        $menu = $this->addressRepo->getOne(intval($last_id ?? 0));
        return retSuc($menu);
    }

    public function detail($id)
    {
        $id = intval($id);
        if (!$id)
            return retFail("参数错误");
        $res = $this->addressRepo->getOne($id);
        return retSuc($res);
    }

    public function delete($id)
    {
        $ids = intval($id);
        if (empty($ids)) {
            return retFail("参数错误");
        }

        $res = $this->addressRepo->getOne(intval($id ?? 0));
        if ($res['code'] == 'SUPER') {
            return retFail($res['name'] . "不允许删除");
        }

        return $this->addressRepo->batchDelete($ids);
    }

    /**
     * 导入地址
     */
    public function import()
    {
        ini_set('memory_limit', '2048M');
        set_time_limit(0);

        $file = request()->file('file');
        if (!$file) {
            return retFail("请选择上传文件");
        }

        $ext = strtolower($file->getClientOriginalExtension());
        if ($ext != 'xlsx') {
            return retFail("只支持xlsx格式的Excel表格");
        }

        $type = request()->get("type", 0);
        try {
            Excel::import(new ImportDataService(intval($type)), $file);
            return retSuc([], "导入成功");
        } catch (Exception $e) {
            return retFail($e->getMessage());
        }

    }


}
